import 'dart:convert';

import 'package:intl/intl.dart';
import 'package:redux/redux.dart';
import 'package:stock_check/common/config/Config.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:stock_check/common/db/SqliteManage.dart';
import 'package:stock_check/common/http/Api.dart';
import 'package:stock_check/common/http/HttpManager.dart';
import 'package:stock_check/common/model/user.dart';
import 'package:stock_check/common/model/userInfo.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/redux/userReducer.dart';
import 'package:stock_check/common/storage/LocalStorage.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';

class UserDao{
  static final formatter = new DateFormat('yyyy-MM-dd');

  // 判断是否需要更新数据
  static Future<bool> needUpdate() async{
    String lastUpdateTime = await LocalStorage.get(Config.LAST_UPDATE);
    String currentTime = formatter.format(DateTime.now());
    return lastUpdateTime != currentTime;
  }

  // 更新本地用户信息
  static initAppInfo(Store store) async{
    // 清除昨天的列表信息
    if(await needUpdate()){
      DataBase dataBase = new DataBase();
      await dataBase.deleteTable();
      await dataBase.deleteTaskTable();
    }

    var res = await getUserInfoLocal();
    if(res!=null && res.result){
      store.dispatch(UpdateUserAction(res.data));
    }
    return DataResult(res.data,res.result);
  }


  // 本地存储用户信息
  static Future<Null> _saveUserInfo(UserInfo userInfo,User user) async{
    String userJson = json.encode(userInfo);
    await LocalStorage.save(Config.USER_INFO, userJson);
    await LocalStorage.save(Config.USER_NAME, user.username);
    await LocalStorage.save(Config.USER_PWD, user.password);
  }

  // 用户登陆
  static Future<DataResult> login(String username,String password) async{
    password = CommonUtils.sha1Encode(password);
    User user = new User(username: username,password: password);
    var res = await HttpManager.netFetch(Api.loginUrl, user.toJson());
    res = json.decode(res.data);
    if(res['result']['resultId']==200) {
      UserInfo userInfo = UserInfo.fromJson(res);
      await _saveUserInfo(userInfo,user);
      return DataResult(userInfo,true);
    }else{
      // 返回错误信息
      return DataResult(res['result']['message'],false);
    }
  }

  // 获取本地登录用户信息
  static getUserInfoLocal() async {
    var userText = await LocalStorage.get(Config.USER_INFO);
    if (userText != null) {
      var userMap = json.decode(userText);
      UserInfo user = UserInfo.fromJson(userMap);
      return DataResult(user, true);
    } else {
      return DataResult(null, false);
    }
  }

  // 退出登录
  static logout(Store<StockState> store) async{
    await LocalStorage.remove(Config.USER_INFO);
    store.dispatch(UpdateUserAction(UserInfo.empty()));
    return DataResult(null,true);
  }
}